package com.ht.api.handler.auth;

import org.springframework.stereotype.Component;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.UserInfo;
import com.ht.api.constant.CacheConstants;
import com.ht.api.db.util.RedisUtil;
import com.ht.api.enums.Status;
import com.ht.api.init.ApiInitializer;
import com.ht.api.util.UserUtil;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

/**
 * 鉴权：功能权限
 * @author asq
 * @createTime 2024年12月22日 16:46:13
 */
@Component
@Slf4j
public class CheckAuthorize implements ICheck {

	@Override
	public AjaxResult check(HttpServletRequest req, HttpServletResponse res) {
		// 获取登陆对象
		UserInfo info = UserUtil.getUserInfo(req);

		// 获取访问url并判断是否需要鉴权
		String url = getUrl(req);

		// 判断权限
		return webCheck(req, info, url);
	}

	/**
	 * WEB鉴权
	 * @param req
	 * @param info
	 * @return
	 */
	private AjaxResult webCheck(HttpServletRequest req, UserInfo info, String url) {
		// 超级管理员不作任何限制
		if (info.isAdmin()) {
			return AjaxResult.success();
		}

		// 判断用户状态
		int userStatus = RedisUtil.get(CacheConstants.KEY_USER_STAT_WEB + info.getId());
		if (Status.DISABLE.getCode() == userStatus) {
			return AjaxResult.error(HttpStatus.HTTP_BAD_REQUEST, "你的帐号已被管理员封禁");
		}

		// 判断权限
		String prems = ApiInitializer.authApis.get(url);
		if (StrUtil.isBlank(prems) || info.getPerms().contains(prems)) {
			return AjaxResult.success();
		}
		return FAULT_AUTHORIZE;
	}

	/**
	 * 获取访问url
	 * @param req
	 * @return
	 */
	private String getUrl(HttpServletRequest req) {
		String url = req.getRequestURI();
		return url.substring(url.indexOf("/"));
	}
}
